<template>
  <div class="statistics-container">

    <div class="page-header">
      <!-- 设备选择 -->
      <div class="device-select-container">
        <span class="device-select-label">设备选择：</span>
        <div class="device-list">
          <div 
            v-for="item in pumpList" 
            :key="item.device_id" 
            class="device-item"
            :class="{ 'device-item-active': pumpSelect && pumpSelect.device_id === item.device_id }"
            @click="handleDeviceSelect(item)"
          >
            <div class="device-item-content">
              <i class="el-icon-monitor device-icon"></i>
              <span class="device-name">{{ item.device_name }}</span>
              <i v-if="pumpSelect && pumpSelect.device_id === item.device_id" class="el-icon-check device-check"></i>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="page-content">
      <el-row :gutter="20">
        <el-col :span="14">
          <div class="echarts-container">
            <!-- 健康评分 -->
            <div class="card health-score">
              <div class="card-header commonFlex" style="padding: 12px 8px;">
                <span class="card-title">
                  <i class="el-icon-data-line"></i>
                  健康评分
                </span>
                <!-- 健康评分计算时间展示 -->
                <span class="health-score-time">
                  <i class="el-icon-time"></i>
                  {{ healthScoreTime || '--' }}
                </span>
              </div>
              <div class="card-body">
                <HealthRadar
                  :key="healthRadarKey"
                  :healthScoreData="healthScoreData"
                  v-if="loading"
                />
              </div>
            </div>
            <!-- 告警分析 -->
            <div class="card alarm-analysis ">
              <div class="card-header commonFlex">
                <span class="card-title">
                  <i class="el-icon-warning"></i>
                  告警分析
                </span>
                <TimeSelect @time-change="handleTimeChange1"></TimeSelect>
              </div>
              <div class="card-body">
                <AlarmAnalysis
                  :key="alarmAnalysisKey"
                  :alarmData="alarmAnalysisData"
                  v-if="loading"
                />
              </div>
            </div>
          </div>
          <!-- 历史健康评分 -->
          <div class="card history-health-score">
            <div class="card-header commonFlex">
              <span class="card-title">
                <i class="el-icon-trend-charts"></i>
                历史健康评分
              </span>
              <TimeSelect @time-change="handleTimeChange2"></TimeSelect>

            </div>
            <div class="card-body">
              <HistoryHealthScore
                :key="historyHealthScoreKey"
                :historyData="historyHealthScoreData"
                v-if="loading"
              />
            </div>
          </div>
        </el-col>

        <el-col :span="10">
          <div class="page-right">
            <!-- 运行分析模块 -->
            <div class="card running-analysis" v-loading="runningAnalysisLoading" element-loading-text="加载中..." element-loading-background="rgba(45, 74, 107, 0.8)">
              <div class="card-header commonFlex">
                <span class="card-title">
                  <i class="el-icon-cpu"></i>
                  运行分析
                </span>
                <TimeSelect @time-change="handleTimeChange3"></TimeSelect>
              </div>
              <div class="card-body">
                <div class="runningAnalysisBox">
                  <div class="runningAnalysisItem" v-for="(item, index) in runningAnalysisData" :key="index">
                    <div class="item-icon" :class="`icon-${index}`">
                      <i :class="getIconClass(index)"></i>
                    </div>
                    <div class="item-content">
                      <div class="item-label">{{ item.label }}</div>
                      <div class="item-value">
                        <span class="value-number">{{ formatValue(item.value) }}</span>
                        <span class="value-unit">{{ item.unit }}</span>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="runningTimeTrend">
                  <runningTimeTrend :key="runtimeTrendKey" :runtimeTrendData="runtimeTrendData" v-if="loading"></runningTimeTrend>
                </div>
              </div>
            </div>

            <!-- 故障记录 -->
            <div class="card fault-record">
              <div class="card-header commonFlex">
                <span class="card-title">
                  <i class="el-icon-document"></i>
                  故障记录
                </span>
                <TimeSelect @time-change="handleTimeChange4"></TimeSelect>
              </div>
              <div class="card-body">
                <el-table :data="faultRecordData" style="width: 100%" size="small" stripe
                  :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: '500', fontSize: '11px', textAlign: 'center', padding: '8px 0', height: '36px' }"
                  :cell-style="{ fontSize: '11px', padding: '6px 0', textAlign: 'center', height: '32px' }">
                  <el-table-column prop="index" label="序号" width="50" align="center">
                    <template slot-scope="scope">
                      {{ scope.$index + 1 }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="description" label="故障描述" align="center" header-align="center"
                    show-overflow-tooltip></el-table-column>
                  <el-table-column prop="reportTime" label="上报时间" align="center"
                    header-align="center"></el-table-column>
                  <el-table-column prop="reportMethod" label="上报方式" align="center"
                    header-align="center"></el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>


  </div>
</template>

<script>
// 导入健康雷达图组件
import HealthRadar from '@/views/statistics/components/healthRadar.vue'
// 导入告警分析组件
import AlarmAnalysis from '@/views/statistics/components/alarmAnalysis.vue'
// 导入历史健康评分组件
import HistoryHealthScore from '@/views/statistics/components/historyHealthScore.vue'
// 导入运行时间趋势组件
import RunningTimeTrend from '@/views/statistics/components/runningTimeTrend.vue'
// 导入API接口
import {
  getHostInfo,
  getHealthScoreData,
  getAlarmAnalysis,
  getHistoryHealthScore,
  getReactivePowerTotal,
  getActivePowerTotal,
  getRuntimeTotal,
  getActiveEnergySummary,
  getRuntimeTrend,
  getFaultRecordList
} from '@/views/statistics/api/screenApi'
import TimeSelect from '@/views/statistics/components/timeSelect.vue'
export default {
  name: 'Statistics',
  components: {
    HealthRadar,
    AlarmAnalysis,
    HistoryHealthScore,
    RunningTimeTrend,
    TimeSelect
  },
  data() {
    return {

      //加载状态
      loading: false,
      //运行分析模块加载状态
      runningAnalysisLoading: false,
      //下拉框选择绑定数据
      pumpSelect: null,
      //下拉框数据
      pumpList: [],

      //告警分析时间范围
      alarmAnalysisScope: 'month',

      //历史健康评分时间范围
      historyHealthScoreScope: 'month',

      //运行分析时间范围
      runningAnalysisScope: 'month',

      //图表数据
      healthScoreData: null,
      // 健康评分对应时间
      healthScoreTime: '--',
      alarmAnalysisData: null,
      historyHealthScoreData: null,
      runtimeTrendData: null,

      //图表刷新key（用于强制刷新组件）
      healthRadarKey: 0,
      alarmAnalysisKey: 0,
      historyHealthScoreKey: 0,
      runtimeTrendKey:0,

      //运行分析数据
      runningAnalysisData: [
        { label: '总运行时长', value: 0, unit: 'h' },
        { label: '无功功率', value: 0, unit: 'kVar' },
        { label: '有功功率', value: 0, unit: 'kW' },
        { label: '总用电量', value: 0, unit: 'kW·h' },
      ],

      //故障记录数据
      faultRecordData: [
        { description: '电机温度异常电机温度异常电机温度异常电机温度异常电机温度异常', reportTime: '2024-01-15 10:30', reportMethod: '自动' },
        { description: '电压波动过大', reportTime: '2024-01-14 14:20', reportMethod: '手动' },
        { description: '设备运行超时', reportTime: '2024-01-13 09:15', reportMethod: '自动' },
      ]
    }
  },
  watch: {
    // 监听设备选择变化，自动刷新数据
    pumpSelect: {
      handler(newVal) {
        if (newVal && newVal.device_id) {
          this.loadAllChartData()
        }
      },
      deep: true
    }
  },
  mounted() {
    this.loadAllData()
  },
  methods: {

    //初始化数据
    async loadAllData() {
      await this.loadHostInfo()
      // 注意：pumpSelect的变化会触发watch，自动加载图表数据，这里不需要手动调用
    },

    // 处理设备选择
    handleDeviceSelect(item) {
      this.pumpSelect = item
    },

    //获取主机信息
    async loadHostInfo() {
      const res = await getHostInfo();
      this.pumpList = res.data.map(item => {
        return {
          device_id: item.device_id,
          device_kg_id: item.device_kg_id,
          device_name: item.device_name,
        }
      });

      //控制视图
      this.loading = true;

      // 如果有数据，默认选中第一项
      if (this.pumpList.length > 0 && !this.pumpSelect) {
        this.pumpSelect = this.pumpList[0]
      }
    },

    // 加载所有图表数据
    async loadAllChartData() {
      if (!this.pumpSelect) {
        return
      }

      try {
        // 并行加载所有图表数据
        await Promise.all([
          this.loadHealthScoreData(),
          this.loadRunningAnalysisData(),
          this.loadAlarmAnalysisData(),
          this.loadHistoryHealthScoreData(),
          this.getFaultRecordList()
        ])
      } catch (error) {
        console.error('加载图表数据失败:', error)
      }
    },

    // 加载健康评分数据
    async loadHealthScoreData() {
      if (!this.pumpSelect || !this.pumpSelect.device_id) {
        return
      }

      try {
        const res = await getHealthScoreData(this.pumpSelect.device_id)
        if (res.code === 200 && res.data && res.data.latest) {
          this.healthScoreData = res.data.latest
          this.healthScoreTime = this.formatScoreTime(res.data.latest.scoreTime)
          // 更新key强制刷新组件
          this.healthRadarKey++
        } else {
          this.healthScoreTime = '--'
        }
      } catch (error) {
        console.error('获取健康评分数据失败:', error)
        this.healthScoreData = null
        this.healthScoreTime = '--'
      }
    },

    // 加载告警分析数据
    async loadAlarmAnalysisData() {
      if (!this.pumpSelect || !this.pumpSelect.device_kg_id) {
        return
      }

      try {
        const res = await getAlarmAnalysis(this.pumpSelect.device_kg_id, this.alarmAnalysisScope)
        if (res.code === 200 && res.data) {
          this.alarmAnalysisData = res.data
          // 更新key强制刷新组件
          this.alarmAnalysisKey++
        }
      } catch (error) {
        console.error('获取告警分析数据失败:', error)
        this.alarmAnalysisData = null
      }
    },

    // 加载历史健康评分数据
    async loadHistoryHealthScoreData() {
      if (!this.pumpSelect || !this.pumpSelect.device_kg_id) {
        return
      }

      try {
        const res = await getHistoryHealthScore(this.pumpSelect.device_id, this.historyHealthScoreScope)
        if (res.code === 200 && res.data && res.data.history) {
          this.historyHealthScoreData = res.data.history
          // 更新key强制刷新组件
          this.historyHealthScoreKey++
        }
      } catch (error) {
        console.error('获取历史健康评分数据失败:', error)
        this.historyHealthScoreData = null
      }
    },
    //加载运行分析数据
    async loadRunningAnalysisData() {
      if (!this.pumpSelect) {
        return
      }

      // 开始加载，显示遮罩
      this.runningAnalysisLoading = true

      try {
        // 并行请求5个运行分析接口，使用 allSettled 确保即使有失败也能处理成功的结果
        const results = await Promise.allSettled([
          // 无功功率总量
          getReactivePowerTotal(this.pumpSelect.device_kg_id, this.runningAnalysisScope),
          // 有功功率总量
          getActivePowerTotal(this.pumpSelect.device_kg_id, this.runningAnalysisScope),
          // 运行时长总量
          getRuntimeTotal(this.pumpSelect.device_kg_id, this.runningAnalysisScope),
          // 用电量汇总
          getActiveEnergySummary(this.pumpSelect.device_kg_id, this.runningAnalysisScope),
          // 运行时长趋势
          getRuntimeTrend(this.pumpSelect.device_kg_id, this.runningAnalysisScope)
        ])

        // 解构结果，每个结果可能是 {status: 'fulfilled', value: ...} 或 {status: 'rejected', reason: ...}
        const [reactivePowerRes, activePowerRes, runtimeRes, energyRes, trendRes] = results.map(result => {
          if (result.status === 'fulfilled') {
            return result.value
          } else {
            console.error('接口请求失败:', result.reason)
            return { code: 500, data: null } // 返回失败标记
          }
        })

        // 更新运行分析数据
        // 1. 更新有功功率
        console.log('activePowerRes',activePowerRes);
        console.log('执行成功!!!!');

        if (activePowerRes.code === 200 && activePowerRes.data) {
          this.runningAnalysisData[2].value = activePowerRes.data.totalActivePowerKw || 0
        }

        // 2. 更新无功功率
        if (reactivePowerRes.code === 200 && reactivePowerRes.data) {
          this.runningAnalysisData[1].value = reactivePowerRes.data.totalReactivePowerKw || 0
        }

        // 3. 更新运行时长
        if (runtimeRes.code === 200 && runtimeRes.data) {
          this.runningAnalysisData[0].value = runtimeRes.data.runtimeHours || 0
        }

        // 4. 更新用电量：从summary数组中根据当前时间范围查找对应的数据
        if (energyRes.code === 200 && energyRes.data?.summary) {
          const item = energyRes.data.summary.find(item => item.scope === this.runningAnalysisScope)
          this.runningAnalysisData[3].value = item?.totalEnergyKwh || 0
        }
        // 5. 更新运行时长趋势
        if (trendRes.code === 200 && trendRes.data) {
          this.runtimeTrendData = trendRes.data.trend;
          this.runtimeTrendKey++
        }
      } catch (error) {
        console.error('获取运行分析数据失败:', error)
        // 请求失败时重置为默认值
        this.runningAnalysisData = [
          { label: '总运行时长', value: 0, unit: 'h' },
          { label: '无功功率', value: 0, unit: 'kVar' },
          { label: '有功功率', value: 0, unit: 'kW' },
          { label: '总用电量', value: 0, unit: 'kW·h' },
        ]
      } finally {
        // 无论成功或失败，都关闭加载遮罩
        this.runningAnalysisLoading = false
      }
    },

    //获取故障记录列表
    async getFaultRecordList(){

      try {
        const res = await getFaultRecordList(this.pumpSelect.device_kg_id, this.runningAnalysisScope)
        if (res.code === 200 && res.rows) {
          this.faultRecordData = res.rows.map(item =>{

            return {

              description: item.faultDescription ||'--',
              // 去除T
              reportTime: item.reportTime.replace('T', ' '),
              reportMethod: item.reportMethod,
            }
          })

          console.log('数据上吧',this.faultRecordData);
        }
      } catch (error) {
        console.error('获取故障记录列表失败:', error)
        this.faultRecordData = []
      }
    },


    //告警分析时间范围改变
    async handleTimeChange1(value) {
      this.alarmAnalysisScope = value
      await this.loadAlarmAnalysisData()
    },

    //历史健康评分时间范围改变
    async handleTimeChange2(value) {
      this.historyHealthScoreScope = value
      await this.loadHistoryHealthScoreData()
    },
    //运行分析时间范围改变
    async handleTimeChange3(value) {
      this.runningAnalysisScope = value
      await this.loadRunningAnalysisData()
    },

    //故障记录时间范围改变
    async handleTimeChange4(value) {
      this.runningAnalysisScope = value
      await this.getFaultRecordList()
    },

    // 格式化数值
    formatValue(value) {
      if (value >= 10000) {
        return (value / 10000).toFixed(2)
      }
      return value.toLocaleString()
    },
    // 格式化健康评分时间
    formatScoreTime(scoreTime) {
      if (!scoreTime) {
        return '--'
      }
      return scoreTime.replace('T', ' ')
    },

    // 获取图标类名
    getIconClass(index) {
      const icons = [
        'el-icon-time',
        'el-icon-lightning',
        'el-icon-thumb',
        'el-icon-data-analysis'
      ]
      return icons[index] || 'el-icon-info'
    }
  }
}
</script>

<style scoped lang="scss">
@import '@/views/statistics/style/screen.scss';

// 自定义运行分析模块的 loading 遮罩样式
.running-analysis {
  ::v-deep .el-loading-mask {
    background-color: rgba(45, 74, 107, 0.8) !important;

    .el-loading-spinner {
      .circular {
        width: 42px;
        height: 42px;
      }

      .path {
        stroke: #409eff;
      }
    }

    .el-loading-text {
      color: #fff;
      font-size: 14px;
    }
  }
}
</style>
